package service.impl.v2;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import dao.v2.ApplyReturnVOMapper;
import dao.v2.ConfigVOMapper;
import dao.v2.MemberCartVOMapper;
import dao.v2.OrderVOMapper;
import model.DicVO;
import model.FileVO;
import model.LogOrder;
import model.LogOrderBack;
import model.MemberVO;
import model.OrderBackItemVO;
import model.OrderBackVO;
import model.OrderGoodVO;
import model.OrderTimer;
import model.OrderVO;
import model.SeqVO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import service.v2.ApplyReturnService;
import service.v2.TimerService;
import util.PackageUtil;

@Service
public class ApplyReturnServiceImpl implements ApplyReturnService {
	@Autowired
	private ApplyReturnVOMapper dao;
	@Autowired
	private OrderVOMapper orderVOMapper;
	@Autowired
	private ConfigVOMapper configVOMapper;
	@Autowired
	private MemberCartVOMapper memberCartVOMapper;
	@Autowired
	private TimerService timerService;
	
	public List<OrderGoodVO> getOrderGoodByOrderId(String order_id) {
		// TODO Auto-generated method stub
		return dao.getOrderGoodByOrderId(order_id);
	}


	public OrderGoodVO getOrderGoodById(String id) {
		// TODO Auto-generated method stub
		return dao.getOrderGoodById(id);
	}


	public void InsertOrderBack(OrderBackVO orderBack) {
		// TODO Auto-generated method stub
		dao.InsertOrderBack(orderBack);
	}


	public OrderBackVO getOrderBackByOrderId(String order_back_id) {
		// TODO Auto-generated method stub
		return dao.getOrderBackByOrderId(order_back_id);
	}


	public List<LogOrder> getLogOrderByOrderId(String order_id) {
		// TODO Auto-generated method stub
		return dao.getLogOrderByOrderId(order_id);
	}


	public boolean judgeOrderBackState(String order_back_id,String state) {
		
		int count = dao.judgeOrderBackState(order_back_id,state);
		if(count>0){
			return true;
		}else{
			return false;
		}
	}


	public List<LogOrderBack> cancelReturn(String order_back_id,String order_id, String member_id) {
		
		// TODO Auto-generated method stub
		
		OrderTimer order_timer  = timerService.getOrderTimerByOrderIdAndState(order_id,"1");
		
		orderVOMapper.delOrderTimer(order_timer.getId());
		
		OrderTimer orderTime = new OrderTimer();
		orderTime.setOrder_id(order_id);
		orderTime.setOpen_yn("Y");
		orderTime.setType("1");
		orderTime.setTime(order_timer.getTime());
		memberCartVOMapper.addOrderTimer(orderTime);
		
		final String order_time_idt = orderTime.getId();
		final String order_idt = order_id;
		final String pay_timert = order_timer.getTime();
		
		 Thread t = new Thread(new Runnable(){  
	            public void run(){  
	            	timerService.orderPayTimer(order_time_idt, order_idt, "", "0", pay_timert, "1");
	            }
	      });  
	       t.start(); 
		//timerService.orderPayTimer(orderTime.getId(), order_id, "", "0", order_timer.getTime(), "1");
		
		LogOrderBack logOrderBack = new LogOrderBack();
		logOrderBack.setOrder_back_id(order_back_id);
		logOrderBack.setMember_id(member_id);
		//logOrderBack.setManager_id("");
		logOrderBack.setRemark("取消申请");
		logOrderBack.setType("0");
		logOrderBack.setCreate_time("");
		dao.addLogOrderBack(logOrderBack);
		//状态 0申请退货 1客服允许退货 2客服拒绝退货申请 3无需退货直接退款 4用户取消退货
		String order_back_state = "4";
		dao.updOrderBackState(order_back_id,order_back_state);
		//修改order 表 state 状态
		//	order  state 状态 1待付款2付款中 3待发货 4待收货 5交易成功 6交易关闭 7退款中
		String order_state = "4";
		dao.updOrderState(order_id,order_state);
		
		//获取日志 并返回
		List<LogOrderBack> logOrderBackList = dao.getLogOrderBackByOrderBackId(order_back_id);
		return logOrderBackList;
	}


	public List<LogOrderBack> getLogOrderBackByOrderBackId(String order_back_id) {
		return dao.getLogOrderBackByOrderBackId(order_back_id);
	}


	public List<DicVO> getDicByParentId(String parent_id) {
		// TODO Auto-generated method stub
		return dao.getDicByParentId(parent_id);
	}


	public void applyRetSub(String member_id,String order_back_id, String ems_id, String ems_no,String order_id) {
		// TODO Auto-generated method stub
		String user_back_time  = configVOMapper.loadConfig("USER_BACK_TIME");
		//存log
		LogOrderBack logOrderBack = new LogOrderBack();
		logOrderBack.setOrder_back_id(order_back_id);
		logOrderBack.setMember_id(member_id);
		//logOrderBack.setManager_id("");
		logOrderBack.setRemark("物流信息已提交，客服会在收到商品后处理退款");
		logOrderBack.setType("4");
		logOrderBack.setCreate_time("");
		dao.addLogOrderBack(logOrderBack);
		
		OrderTimer orderTime = new OrderTimer();
		orderTime.setOrder_id(order_id);
		orderTime.setOpen_yn("Y");
		orderTime.setType("2");
		orderTime.setTime(user_back_time);
		orderTime.setOrder_back_id(order_back_id);
		memberCartVOMapper.addOrderTimer(orderTime);
		
		final String order_time_idt = orderTime.getId();
		final String order_idt = order_id;
		final String pay_timert = user_back_time;
		final String order_back_idt = order_back_id;
		 Thread t = new Thread(new Runnable(){  
	            public void run(){  
	            	/*
	            	 * 	order_timer_id 定时器ID
	            	 * 	order_id       订单ID
	            	 * 	order_back_id  退货ID 
	            	 * 	timer_state    0 订单 1 退货
	            	 * 	senconds       秒数
	            	 * 	type           定时器TYPE
	            	 */
	            	timerService.orderPayTimer(order_time_idt, order_idt, order_back_idt, "1", pay_timert, "2");
	            }
	      });  
	       t.start(); 
	       
		//timerService.orderPayTimer(orderTime.getId(), order_id, order_back_id, "1", user_back_time, "2");
		//update order_back
		dao.updOrderBackEms(order_back_id,ems_id,ems_no);
	}


	public OrderVO getOrderByOrderId(String order_id) {
		// TODO Auto-generated method stub
		return dao.getOrderByOrderId(order_id);
	}


	public Map<String, Object> addOrderBack(MemberVO member,String data,String order_id,String address_name,String address_tel,String member_id) {
		// TODO Auto-generated method stub
		
		//修改order 表 state 状态
		String order_state = "7";
		//dao.updOrderState(order_id,order_state);
		int countUpdState = dao.updOrderStateFaster(order_id,"4",order_state);
		if(countUpdState>0){
			JSONArray Json = JSONArray.fromObject(data);
			double back_price  = 0;
			for (int i = 0; i < Json.size(); i++) {
				JSONObject obj = (JSONObject) Json.get(i);
				obj.get("order_good_id").toString();
				obj.get("num").toString();
				double price = orderVOMapper.getBackPrice(obj.get("order_good_id").toString(),obj.get("num").toString());
				back_price = back_price + price;
			}
			//修改剩余时间
			//order_back
			List<OrderTimer> orderTimerlist = orderVOMapper.getTimerOrder(member.getId(),order_id);
			for (int i = 0; i < orderTimerlist.size(); i++) {
				if(orderTimerlist.get(i).getType().equals("1")){
					orderVOMapper.updOrderTimerYn(orderTimerlist.get(i).getId(),"N");
				}
			}
			
			OrderVO ordervo = orderVOMapper.getOrderById(order_id);
			OrderBackVO orderBack = new OrderBackVO();
			orderBack.setOrder_id(order_id);
			orderBack.setState("0");
			orderBack.setName(address_name);
			orderBack.setTel(address_tel);
			orderBack.setTotal_price(String.valueOf(Double.parseDouble(ordervo.getTotal_price())+Double.parseDouble(ordervo.getFreight()==null?"0":ordervo.getFreight())));
			orderBack.setBack_price(String.valueOf(back_price));
		
			
			//存入 order back 
			dao.InsertOrderBack(orderBack);
			String order_back_id  = orderBack.getId();
			
			for (int i = 0; i < Json.size(); i++) {
				JSONObject obj = (JSONObject) Json.get(i);
				JSONArray fileList =  (JSONArray) obj.get("file");
				SeqVO seq = new SeqVO();
				dao.getSeq(seq);
				String folder_id = seq.getSeq();
				
				for (int j = 0; j < fileList.size(); j++) {
					FileVO fileVO = new FileVO();
					fileVO.setCat_id("194");
					fileVO.setPath(fileList.get(j).toString());
					fileVO.setFolder_id(folder_id);
					dao.addFile(fileVO);
					//dao.addFileFolder(folder_id,fileVO.getId());
				}
				
				OrderBackItemVO orderBackItem = new OrderBackItemVO();
				orderBackItem.setOrder_back_id(order_back_id);
				orderBackItem.setOrder_good_id(obj.get("order_good_id").toString());
				orderBackItem.setNum(obj.get("num").toString());
				orderBackItem.setState("0");
				orderBackItem.setReason(obj.get("reason").toString());
				orderBackItem.setRemark(obj.get("detail").toString());
				orderBackItem.setFold_id(folder_id);
				
		
				//存入 order back item
				dao.InsertOrderBackItem(orderBackItem);
				
			}
			
			LogOrderBack logOrderBack = new LogOrderBack();
			logOrderBack.setOrder_back_id(order_back_id);
			logOrderBack.setMember_id(member.getId());
			logOrderBack.setRemark("退货申请已提交，等待客服受理，通常需要1-2个工作日");
			logOrderBack.setType("0");
			dao.addLogOrderBack(logOrderBack);
			
			
			//获取日志 并返回
			List<LogOrderBack> logOrderBackList = dao.getLogOrderBackByOrderBackId(order_back_id);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("state", "200");
			map.put("msg", "successs");
			map.put("result", logOrderBackList);
			map.put("remark", "");
			
			return map;
		}else{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("state", "201");
			map.put("msg", "");
			map.put("result", "");
			map.put("remark", "");
			return map;
		}
		
	}
	
}
